package projet.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;

@Entity
@Table(name="course")
@NamedQueries({
    @NamedQuery(name="Course.findAll", query="SELECT c FROM Course c ORDER BY c.code"),
    @NamedQuery(name="Course.findByCode", query="SELECT c FROM Course c WHERE c.code like :code"),
    @NamedQuery(name="Course.findSessions", query="SELECT s FROM Session s WHERE s.course.code = :code ORDER BY s.start, s.end, s.id"),
    @NamedQuery(name="Course.findSessionsFuture", query="SELECT s FROM Session s WHERE s.course.code = :code AND s.start > CURRENT_DATE ORDER BY s.start, s.end, s.id"),
    @NamedQuery(name="Course.findAllByTitle", query="SELECT c FROM Course c WHERE c.title like :title ORDER BY c.code"),
    @NamedQuery(name="Course.findAllByLocation", query="SELECT DISTINCT c FROM Course c INNER JOIN c.sessions s WHERE s.location.id = :locationId ORDER BY c.code"),
    @NamedQuery(name="Course.findAllByDate", query="SELECT DISTINCT c FROM Course c INNER JOIN c.sessions s WHERE :date BETWEEN s.start AND s.end ORDER BY c.code"),
    @NamedQuery(name="Course.findAllByTitleAndLocation", query="SELECT DISTINCT c FROM Course c INNER JOIN c.sessions s WHERE c.title LIKE :title AND s.location.id = :locationId ORDER BY c.code"),
    @NamedQuery(name="Course.findAllByTitleAndDate", query="SELECT DISTINCT c FROM Course c INNER JOIN c.sessions s WHERE c.title LIKE :title AND :date BETWEEN s.start AND s.end ORDER BY c.code"),
    @NamedQuery(name="Course.findAllByLocationAndDate", query="SELECT DISTINCT c FROM Course c INNER JOIN c.sessions s WHERE s.location.id = :locationId AND :date BETWEEN s.start AND s.end ORDER BY c.code"),
    @NamedQuery(name="Course.findAllByTitleAndLocationAndDate", query="SELECT DISTINCT c FROM Course c INNER JOIN c.sessions s WHERE c.title LIKE :title AND s.location.id = :locationId AND :date BETWEEN s.start AND s.end ORDER BY c.code")})
public class Course {
	
	@Id
	private String code;
	
	@Column(nullable=false)
	private String title;

	@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "course")
	private List<Session> sessions;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setSessions(List<Session> sessions) {
		this.sessions = sessions;
	}

	public List<Session> getSessions() {
		return sessions;
	}
	
	public void addSession(Session s) {
		if (sessions == null) {
			sessions = new ArrayList<Session>();
		}
		s.setCourse(this);
		sessions.add(s);
	}

}
